/**
 * 图数据结构 - 重构自原始的graph.js
 */
export class Graph {
  constructor(settings = {}) {
    this.nodes = {}
    this.edges = {}
    this.settings = {
      epoch: 'Event Time',
      epochFormat: 'YYYY-M-D H:m:s',
      source: 'source',
      target: 'target',
      ...settings
    }
    
    this.nodesCount = 0
    this.edgesCount = 0
  }

  /**
   * 获取节点
   */
  getNode(nodeId) {
    return this.nodes[nodeId]
  }

  /**
   * 获取边
   */
  getEdge(source, target) {
    return this.edges[source + '<>' + target] || this.edges[target + '<>' + source]
  }

  /**
   * 添加节点
   */
  addNode(nodeName, nodeData) {
    if (!nodeName) {
      return null
    }

    let node = this.getNode(nodeName)

    if (!node) {
      node = new Node(this.nodesCount, nodeName)
      this.nodesCount++
      this.nodes[nodeName] = node
    }

    if (nodeData) {
      node.data.push(nodeData)
    }

    return node
  }

  /**
   * 添加边
   */
  addEdge(source, target, data) {
    // 防止自环
    if (source === target) {
      this.addNode(source, data)
      return
    }

    const fromNode = this.addNode(source, data)
    const toNode = this.addNode(target, data)

    if (fromNode && toNode) {
      // 记录节点的邻接关系
      if (!fromNode.edges.includes(toNode.id)) {
        fromNode.edges.push(toNode.id)
      }
      if (!toNode.edges.includes(fromNode.id)) {
        toNode.edges.push(fromNode.id)
      }

      // 创建边
      this.createEdge(source, target, data)
    }
  }

  /**
   * 创建边
   */
  createEdge(source, target, data) {
    let edge = this.getEdge(source, target)

    if (!edge) {
      edge = new Edge(source, target, this.edgesCount)
      this.edgesCount++
      this.edges[source + '<>' + target] = edge
    }

    if (data) {
      edge.data.push(data)
    }

    return edge
  }

  /**
   * 从CSV行添加数据
   */
  addCSVRow(data) {
    const source = data[this.settings.source]
    const target = data[this.settings.target]
    this.addEdge(source, target, data)
  }

  /**
   * 获取节点和边的数组表示
   */
  getNodesAndEdgesArray() {
    const edgesArray = []

    Object.values(this.nodes).forEach(node => {
      edgesArray[node.id] = [...new Set(node.edges)] // 去重
    })

    return edgesArray
  }

  /**
   * 获取查找表
   */
  getLookupTable(nodesWidth) {
    const lookupTable = {}
    let i = 0

    Object.entries(this.nodes).forEach(([key, node]) => {
      const texStartX = (i % nodesWidth) / nodesWidth
      const texStartY = Math.floor(i / nodesWidth) / nodesWidth

      lookupTable[key] = {
        texPos: [texStartX, texStartY],
        id: node.id
      }

      i++
    })

    return lookupTable
  }

  /**
   * 获取时间纹理数组
   */
  getEpochTextureArray(type) {
    const source = type === 'nodes' ? this.nodes : this.edges
    const epochArray = []

    Object.values(source).forEach(item => {
      const epochs = []
      
      item.data.forEach(dataItem => {
        if (dataItem[this.settings.epoch]) {
          const time = this.parseTime(dataItem[this.settings.epoch])
          if (time) {
            epochs.push(time)
          }
        }
      })

      epochArray[item.id] = [...new Set(epochs)] // 去重
    })

    return epochArray
  }

  /**
   * 解析时间
   */
  parseTime(timeString) {
    try {
      // 简化的时间解析，支持多种格式
      const date = new Date(timeString)
      return date.getTime() / 1000 // 返回Unix时间戳
    } catch (error) {
      console.warn('无法解析时间:', timeString)
      return null
    }
  }

  /**
   * 获取节点位置数组
   */
  getNodePositions() {
    const positions = []
    const nodeArray = Object.values(this.nodes).sort((a, b) => a.id - b.id)
    
    nodeArray.forEach(node => {
      // 初始化随机位置
      positions.push(
        (Math.random() - 0.5) * 1000,
        (Math.random() - 0.5) * 1000,
        (Math.random() - 0.5) * 1000
      )
    })
    
    return positions
  }

  /**
   * 获取边的索引数组
   */
  getEdgeIndices() {
    const indices = []
    
    Object.values(this.edges).forEach(edge => {
      const sourceNode = this.getNodeByName(edge.source)
      const targetNode = this.getNodeByName(edge.target)
      
      if (sourceNode && targetNode) {
        indices.push(sourceNode.id, targetNode.id)
      }
    })
    
    return indices
  }

  /**
   * 根据名称获取节点
   */
  getNodeByName(name) {
    return this.nodes[name]
  }

  /**
   * 获取统计信息
   */
  getStats() {
    return {
      nodeCount: this.nodesCount,
      edgeCount: this.edgesCount,
      totalDataPoints: Object.values(this.edges).reduce((sum, edge) => sum + edge.data.length, 0)
    }
  }
}

/**
 * 节点类
 */
export class Node {
  constructor(id, name) {
    this.id = id
    this.name = name
    this.edges = [] // 邻接节点的ID列表
    this.data = [] // 节点相关的数据
    this.position = { x: 0, y: 0, z: 0 } // 3D位置
    this.velocity = { x: 0, y: 0, z: 0 } // 速度
    this.color = { r: 1, g: 1, b: 1 } // 颜色
  }

  /**
   * 添加邻居
   */
  addNeighbor(nodeId) {
    if (!this.edges.includes(nodeId)) {
      this.edges.push(nodeId)
    }
  }

  /**
   * 获取度数
   */
  getDegree() {
    return this.edges.length
  }

  /**
   * 设置位置
   */
  setPosition(x, y, z) {
    this.position.x = x
    this.position.y = y
    this.position.z = z
  }

  /**
   * 设置颜色
   */
  setColor(r, g, b) {
    this.color.r = r
    this.color.g = g
    this.color.b = b
  }
}

/**
 * 边类
 */
export class Edge {
  constructor(source, target, id) {
    this.source = source
    this.target = target
    this.id = id
    this.data = [] // 边相关的数据
    this.weight = 1 // 权重
    this.color = { r: 0.4, g: 0.4, b: 0.4 } // 颜色
  }

  /**
   * 获取权重（基于数据点数量）
   */
  getWeight() {
    return this.data.length
  }

  /**
   * 设置颜色
   */
  setColor(r, g, b) {
    this.color.r = r
    this.color.g = g
    this.color.b = b
  }

  /**
   * 获取时间范围
   */
  getTimeRange() {
    const times = this.data.map(item => {
      if (item['Event Time']) {
        return new Date(item['Event Time']).getTime() / 1000
      }
      return null
    }).filter(time => time !== null)

    if (times.length === 0) return null

    return {
      min: Math.min(...times),
      max: Math.max(...times)
    }
  }
}
